package com.turtle.learning.contents.rocketmq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.turtle.learning.contents.dto.AuditDTO;
import com.turtle.learning.contents.entity.RocketmqTransactionLog;
import com.turtle.learning.contents.mapper.RocketmqTransactionLogMapper;
import com.turtle.learning.contents.service.impl.ShareServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

import java.util.Objects;

/**
 * 用户添加积分消费者-事务
 *
 * @author turtle
 * @since: 2020-04-30
 */
@RocketMQTransactionListener(txProducerGroup = "add-bonus-group")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AddBonusTransactionListener implements RocketMQLocalTransactionListener {
    private final ShareServiceImpl shareService;
    private final RocketmqTransactionLogMapper rocketmqTransactionLogMapper;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        MessageHeaders headers = message.getHeaders();
        String transactionId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);
        try {
            Integer shareId = Integer.valueOf((String) Objects.requireNonNull(headers.get("share_id")));
            shareService.auditByIdWithRocketMqLog(shareId, (AuditDTO) arg, transactionId);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {

        MessageHeaders headers = message.getHeaders();
        String transactionId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);
        QueryWrapper<RocketmqTransactionLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RocketmqTransactionLog::getTransactionId, transactionId);
        RocketmqTransactionLog rocketmqTransactionLog = rocketmqTransactionLogMapper.selectOne(queryWrapper);
        if (rocketmqTransactionLog != null) {
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;

    }
}
